/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>
#include "iservice_registry.h"
#include "i_sle_host.h"
#include "sle_seek_impl.h"
#include "sle_common_config.h"
#include "sle_hilog.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
SleSeek::SleSeekImpl::SleSeekImpl()
{
    SLE_LOGI("SleSeekImpl In");

    callbackImpl_ = new SleSeekCallbackStubImpl(*this);
    SLE_ASSERT_AND_RETURN_LOG(callbackImpl_ != nullptr, "callbackImpl_ is null");

    auto resetCallback = [this](const wptr<IRemoteObject> &remote) { this->ResetService(remote); };
    deathRecipient_ = new SleDeathRecipient(resetCallback);
    SLE_ASSERT_AND_RETURN_LOG(deathRecipient_, "deathRecipient null error!");

    std::lock_guard<std::mutex> lock(mutexProxy_);
    GetProxy();
    SLE_ASSERT_AND_RETURN_LOG(proxy_ != nullptr, "proxy_ is null");
}

SleSeek::SleSeekImpl::~SleSeekImpl()
{
    SLE_LOGI("~SleSeekImpl In");
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "seek proxy null error!");
    SLE_ASSERT_AND_RETURN_LOG(callbackImpl_, "callbackImpl null error!");
    SleErrorCode ret = proxy_->UnregisterSeekCallback(callbackImpl_);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "unregister seek callback failed(%{public}d)!", ret);
}

void SleSeek::SleSeekImpl::GetProxy()
{
    if (proxy_) {
        return;
    }
    sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    SLE_ASSERT_AND_RETURN_LOG(samgr, "no samgr error!");

    sptr<IRemoteObject> hostRemote = samgr->GetSystemAbility(KH_SLE_SERVICE_SYS_ABILITY_ID_);

    SLE_ASSERT_AND_RETURN_LOG(hostRemote, "no remote error!");
    sptr<ISleHost> hostProxy = iface_cast<ISleHost>(hostRemote);
    SLE_ASSERT_AND_RETURN_LOG(hostProxy, "host proxy null error!");

    sptr<IRemoteObject> remote = hostProxy->GetSleServerRemote(SLE_SEEK_SERVER);
    SLE_ASSERT_AND_RETURN_LOG(remote, "no remote error!");

    SLE_ASSERT_AND_RETURN_LOG(deathRecipient_, "deathRecipient null error!");
    SLE_ASSERT_AND_RETURN_LOG(!((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))),
        "Failed to add death recipient");

    proxy_ = iface_cast<ISleSeek>(remote);
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "no seel proxy error!");
    SleErrorCode ret = proxy_->RegisterSeekCallback(callbackImpl_);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "register seek callback failed(%{public}d)!", ret);
    SLE_LOGI("GetProxy success");
}

void SleSeek::SleSeekImpl::ResetService(const wptr<IRemoteObject> &remote)
{
    SLE_ASSERT_AND_RETURN_LOG(remote != nullptr, "remote null error!");
    std::lock_guard<std::mutex> lock(mutexProxy_);
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "no proxy error!");
    sptr<IRemoteObject> serviceRemote = proxy_->AsObject();
    if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) {
        serviceRemote->RemoveDeathRecipient(deathRecipient_);
        proxy_ = nullptr;
        int tryTime = 5;
        while ((!proxy_) && tryTime > 0) {
            sleep(GET_PROXY_SLEEP_SEC);
            tryTime--;
            GetProxy();
        }
    }
}

SleErrorCode SleSeek::SleSeekImpl::CheckOperation()
{
    std::lock_guard<std::mutex> lock(mutexProxy_);
    GetProxy();
    SLE_ASSERT_AND_RETURN_RET_LOG(proxy_, SLE_ERR_INTERNAL_WRONG, "proxy null error!");
    return SLE_NO_ERROR;
}

SleSeek::SleSeek()
{
    SLE_LOGI("SleSeek In");
    pimpl_ = std::make_unique<SleSeekImpl>();
    SLE_ASSERT_AND_RETURN_LOG(pimpl_, "pimpl null error!");
}

SleSeek::~SleSeek()
{
    SLE_LOGI("~SleSeek In");
}

SleSeek &SleSeek::GetDefaultSeek()
{
    static SleSeek seekInstance;
    return seekInstance;
}

SleErrorCode SleSeek::StartSeek(const SleSeekParam &param)
{
    SLE_LOGD("StartSeek In");
    SleErrorCode ret = SeekParam::CheckSeekParam(param);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check param failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "check operation failed(%{public}d)!", ret);

    SeekParam params(param);
    ret = pimpl_->proxy_->StartSeek(params);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "start sle seek failed(%{public}d)!", ret);

    std::unique_lock<std::mutex> lock(pimpl_->mtx_);
    auto status = pimpl_->conditionVariable_.wait_for(
        lock, std::chrono::milliseconds(3000), [this] { return pimpl_->ready_; });
    pimpl_->ready_ = false;
    if (!status) {
        SLE_LOGE("timeout, start sle seek failed!");
        return SLE_ERR_TIME_OUT;
    }
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->state_ == SLE_SEEK_ENABLED_STATE, SLE_ERR_FAILED,
        "start seek failed(%s)!", SleSeekStateStr(pimpl_->state_));
    return SLE_NO_ERROR;
}

SleErrorCode SleSeek::StopSeek()
{
    SLE_LOGD("StopSeek In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->proxy_->StopSeek();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "stop sle seek failed(%{public}d)!", ret);

    std::unique_lock<std::mutex> lock(pimpl_->mtx_);
    auto status = pimpl_->conditionVariable_.wait_for(
        lock, std::chrono::milliseconds(3000), [this] { return pimpl_->ready_; });
    pimpl_->ready_ = false;
    if (!status) {
        SLE_LOGE("timeout, stop sle seek failed!");
        return SLE_ERR_TIME_OUT;
    }
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->state_ == SLE_SEEK_DISABLED_STATE, SLE_ERR_FAILED,
        "stop seek failed(%s)!", SleSeekStateStr(pimpl_->state_));
    return SLE_NO_ERROR;
}

SleErrorCode SleSeek::GetDefaultSeekParamConfig(SleSeekParam &seekConfig)
{
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    ret = pimpl_->proxy_->GetDefaultSeekParamConfig(seekConfig);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get seek param config failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleSeek::RegisterSeekCallback(std::shared_ptr<SleSeekCallback> callback)
{
    SLE_LOGD("RegisterSeekCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback != nullptr, SLE_ERR_INVALID_PARAM, "param callback nullptr error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->callbacks_.Register(callback), SLE_ERR_FAILED,
        "register seek callback failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSeek::UnregisterSeekCallback(std::shared_ptr<SleSeekCallback> callback)
{
    SLE_LOGD("UnregisterSeekCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback != nullptr, SLE_ERR_INVALID_PARAM, "param callback nullptr error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->callbacks_.Unregister(callback), SLE_ERR_FAILED,
        "unregister seek callback failed!");
    return SLE_NO_ERROR;
}
} // SleStandard
} // NearLink
} // OHOS